<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mgmt extends CI_Controller {

	public $data 	= 	array();

	function __construct()
    {     	
        parent::__construct();
		$this->load->helper('idtovalue'); 
		$this->load->helper('url');
		$this->load->helper('position');
		$this->load->helper('form');
		$this->load->model('muser'); 
		$this->load->model('partner');
		$this->load->model('deal');
		$this->load->model('adeal');
		$this->load->model('coupon');
		$this->load->model('category');
		$this->load->model('comment');
		$this->load->model('product');
		$this->load->model('banner');
		$this->load->helper('date'); 
	
		$this->checkSession();
		$this->load->helper('ckeditor');
		$this->load->helper('mail_body');

		$this->load->library('email');

		$config['protocol'] = 'smtp';
		$config['charset'] = 'utf-8';
		$config['wordwrap'] = TRUE;
		$config['mailtype'] = 'html';
		$config['smtp_host'] = 'godeal.kz';
		$config['smtp_port'] = "25";
		$config['smtp_user'] = 'no-reply@godeal.kz';
		$config['smtp_pass'] = 'e5dd1998';
		$this->email->initialize($config);
	}

    public function checkSession() {
    	
    	if (uri_string()!='mgmt/login/banned' && uri_string()!='mgmt/login' && uri_string()!='mgmt/login#' && uri_string()!='mgmt/login/error' && uri_string()!='mgmt/checkUser' && uri_string()!='mgmt/error' && !$this->session->userdata('mid')) {
				header('Location: /mgmt/login#');	
    	} else
    	if ($this->session->userdata('mid')) {
    		if ($this->muser->getLastEntered($this->session->userdata('mid'))!='BLOCKED')
    		$this->muser->setLastEntered($this->session->userdata('mid'),time()); else {
    			$this->session->sess_destroy();
				header('Location: /mgmt/login/banned');
    		}
    	}
    	
    }

    

    public function checkPermission() {
    	if (!hasPermission(uri_string(),$this->session->userdata('mposition'))) {
    		$this->load->view('mgmt/res/error-access.php');
    		return false;
    	}
    	return true;
    }


	public function index(){	
		if ($this->checkPermission()) {
			$this->load->view('mgmt/index.php');
		}
	}

	public function asd(){
		if ($this->checkPermission()) {
			$this->load->view('mgmt/ckeditor.php', $this->data);	
		}
	}

	public function sendEmail($from,$name,$to,$subject,$message){				
		if ($this->checkPermission()) {
		$this->email->set_newline("\r\n");
		$this->email->from($from, $name);
		$this->email->to($to); 
		
		$this->email->subject($subject);
		$this->email->message($message);	

		if ($this->email->send()) {
			echo "Sended Successfully";
		} else {
			echo $this->email->print_debugger();
		}
	}
	}
	
	//----------------------Deal---------------------

	public function allDeals() {
		if ($this->checkPermission()) {
		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		$data["session_name"] = $this->session->userdata('mname');
		$data["session_position"] = $this->session->userdata('mposition');
		$data["last_page"] = $this->deal->pageCount();
		$data["deals"] = $this->deal->getPageDeals($data["page"]);
		$this->load->view('mgmt/res/allDeals.php', $data);	
	}
	}

	public function addDeal() {
		if ($this->checkPermission()) {
		$data["partners"] = $this->partner->getPartnersIdNames();
		$this->load->view('mgmt/res/addDeal.php', $data);
	}
	}

	public function editDeal(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$data["deal"] = $this->deal->getDealById($param);
		
		$this->load->view('mgmt/res/editDeal.php', $data);
	}
	}

	public function editDealPerform(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->deal->editDeal($param, $_POST['partner'], $_POST['partner_id'], $_POST['city'], $_POST['dealname'], $_POST['description'], $_POST['placename'], $_POST['companyname'],
     		$_POST['deal_date_start'], $_POST['coupon_date_start'], $_POST['deal_date_finish'], $_POST['phone'],
     		$_POST['address'], $_POST['p_name'], $_POST['p_email'],
      		$_POST['schedule'],  $_POST['coupon-type'], $this->session->userdata('mname'), 1);
		header('Location: /mgmt/#allDeals/page/1');
	}
	}

	public function addDealPerform() {
		if ($this->checkPermission()) {
		$res['partner'] = $this->partner->getPartnerById($_POST['partner_id']);

		$this->deal->addDeal($res['partner'][0]->name, $_POST['partner_id'], $_POST['city'], $_POST['dealname'], $_POST['description'], $_POST['placename'], $_POST['companyname'],
                   $_POST['deal_date_start'], $_POST['coupon_date_start'], $_POST['deal_date_finish'], $_POST['phone'], $_POST['address'], $_POST['p_name'], $_POST['p_email'],
                   $_POST['schedule'], $_POST['coupon-type'], $this->session->userdata('mname'), 1);
		header('Location: /mgmt/#allDeals/page/1');
	}
	}

	public function acceptDeal(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->db->where('id', $param);
    	$this->db->set('status','2');
		$this->db->update('deals');
		echo "<h2>Успешно подтверждено!</h2>";
		echo "<a class='btn btn-success'href='#allDeals/page/1'>Далее</a>";
	}
	}
	
	public function blockDeal(){
		if ($this->checkPermission()) {
			$param = func_get_arg(1);
			$this->db->where('id', $param);
			$this->db->set('status', '5');
			$this->db->update('deals');
			echo "<h2>Акция отвергнута!</h2>";
			echo "<a class='btn btn-success'href='#allDeals/page/1'>Далее</a>";
		}
	}

	public function sendToCorrectionDeal(){
		if ($this->checkPermission()) {
			$param = func_get_arg(1);
			$this->db->where('id', $param);
			$this->db->set('status', '4');
			$this->db->update('deals');
			echo "<h2>Акция отправлена на исправление!</h2>";
			echo "<a class='btn btn-success'href='#allDeals/page/1'>Далее</a>";
		}
	}

	public function markAsDone(){
		if ($this->checkPermission()) {
			$param = func_get_arg(1);
			$this->db->where('id', $param);
			$this->db->set('status', '3');
			$this->db->update('deals');
			echo "<h2>Акция на сайте!</h2>";
			echo "<a class='btn btn-success'href='#allDeals/page/1'>Далее</a>";
		}
	}

	public function deleteDeal(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->db->delete('deals', array('id' => $param));
		echo "<h2>Акция удалена!</h2>";
		echo "<a class='btn btn-success'href='#allDeals/page/1'>Далее</a>";
	}
	}

	public function viewDeal(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$data["deal"] = $this->deal->getDealById($param);
		$this->load->view('mgmt/res/viewDeal.php', $data);
	}
	}

	//--------------------------Product---------------

	public function products(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$data['products'] = $this->product->getProductsByDealId($param);
		$data['deal_id'] = func_get_arg(1);
		$this->load->view('mgmt/res/products.php', $data);	
	}
	}

	public function addProduct(){
		if ($this->checkPermission()) {
		$data['deal_id'] = func_get_arg(1);
		$this->load->view('mgmt/res/addProduct.php', $data);
	}
	}

	public function addProductPerform(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->product->addProduct($param, $_POST['name'], $_POST['cost'],
			$_POST['discount'],$_POST['price_before'], $_POST['comission']);
		header('Location: /mgmt/#products/did/'.func_get_arg(1));
	}
	}

	public function deleteProductPerform(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->product->deleteProduct($param);
		echo "Удалено";
	}
	}

	public function deleteComment(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->comment->deleteComment($param);
		echo "Удалено";
	}
	}

	public function editProduct(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$data['product'] = $this->product->getProductById($param);
		$this->load->view('mgmt/res/editProduct.php', $data);
	}
	}

	public function editProductPerform(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->product->editProduct($param, $_POST['deal_id'], $_POST['name'],
		 $_POST['cost'], $_POST['discount'], $_POST['price_before'], $_POST['comission']);
		header('Location: /mgmt/#products/did/'.$_POST['deal_id']);
	}
	}

	//-----------------Users----------------

	public function addUser() {
		if ($this->checkPermission()) {
		$this->load->view('mgmt/res/addUser.php');
	}
	}

	public function editUser() {
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$data["muser"] = $this->muser->getUserById($param);
		$this->load->view('mgmt/res/editUser.php', $data);
	}
	}

	public function editUserPerform(){
		if ($this->checkPermission()) {
		$pass = md5($_POST['pass']);
		$param = func_get_arg(1);
		$this->muser->editUser($param, $_POST['name'], 
			$_POST['email'],$_POST['position']
			,$pass);
		header('Location: /mgmt/#allUsers/page/1');
	}
	}

	public function allUsers() {
		if ($this->checkPermission()) {
		$data["last_page"] = $this->muser->pageCount();
		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		$data["session_position"] = $this->session->userdata('mposition');
		$data["musers"] = $this->muser->getPageUsers($data["page"]);
		$this->load->view('mgmt/res/allUsers.php', $data);	
	}
	}

	public function allReports() {
		if ($this->checkPermission()) {
		$data["last_page"] = 10;
		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}

		$this->load->view('mgmt/res/allReports.php', $data);	
	}
	}

	public function addUserPerform(){
		if ($this->checkPermission()) {
		$pass = md5($_POST['pass']);
		$this->muser->addUser($_POST['name'], 
			$_POST['email'],$_POST['position']
			,$pass);

		$this->email->from('no-reply@godeal.kz', 'GoDeal');
		$this->email->to($_POST['email']);

		$this->email->subject('GoDeal | Привет, камрад!');
		$this->email->message(generateRegisteredManagerMessage($_POST['name'], $_POST['email'], $_POST['pass']));	

		$this->email->send();

		header('Location: /mgmt/#allUsers/page/1');
	}
	}

	public function deleteConfirm(){
		if ($this->checkPermission()) {
		echo "<h2>Вы точно хотите удалить сотрудника из базы?</h2>";
		echo "<a class='btn btn-success' href='#deletePerform/id/".func_get_arg(1)."'>Точно </a> <a class='btn btn-cancel' href='#allUsers/page/1'>Назад</a> ";
	}
	}

	public function deletePerform(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->db->delete('musers', array('id' => $param));

		echo "<h2>Успешно удалено!</h2>";
		echo "<a class='btn btn-success'href='#allUsers/page/1'>Далее</a>";
	}
	}

	//-------------Partner-----------
	public function addPartner() {
		if ($this->checkPermission()) {
		$this->load->view('mgmt/res/addPartner.php');	
	}
	}

	public function allPartners() {
		if ($this->checkPermission()) {
		$data["last_page"] = $this->partner->pageCount();
		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}

		$data["session_id"] = $this->session->userdata('mid');
		$data["partners"] = $this->partner->getPagePartners($data["page"]);
		$this->load->view('mgmt/res/allPartners.php', $data);	
	}
	}

	public function deletePartner(){
		if ($this->checkPermission()) {
		$param =  func_get_arg(1);
		$this->db->delete('partners', array('id' => $param));
		echo "<h2>Успешно Удалено!</h2>";
		echo "<a class='btn btn-success'href='#allPartners/page/1'>Далее</a>";
	}
	}

	public function editPartner(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$data["partner"] = $this->partner->getPartnerById($param);
		$this->load->view('mgmt/res/editPartner.php', $data);
	}
	}

	public function editPartnerPerform(){
		if ($this->checkPermission()) {
		$pass = md5($_POST['pass']);
		$param = func_get_arg(1);
		$this->partner->editPartner($param, $_POST['name'], 
			$_POST['tel'],$_POST['email']
			,$pass);
		header('Location: /mgmt/#allPartners/page/1');
	}
	}

	//-----------------Login--------------------
	public function login() {
	if ($this->checkPermission()) {	
		if ($this->session->userdata('mid')) {
			header('Location: /mgmt/');
		} else {

			if ((func_num_args()>0) && (func_get_arg(0) == "error")) {
				
				$data["error"] = "Неверный email или пароль";
				$this->load->view('mgmt/login.php',$data);
			} else 
			if ((func_num_args()>0) && (func_get_arg(0) == "banned")) {
				
				$data["error"] = "Ваш аккаунт заблокирован";
				$this->load->view('mgmt/login.php',$data);
			}
			else $this->load->view('mgmt/login.php');
			
		}
	}
	}

	public function checkUser() {
		if ($this->checkPermission()) {
		$this->load->model('muser');
		if ($user = $this->muser->userExist($_POST['email'],md5($_POST['pass']))) {
			
			if (($this->muser->getLastEntered($user[0]->id)=='BLOCKED')||(time()-intval($this->muser->getLastEntered($user[0]->id))<2400)) {
				$this->muser->setLastEntered($user[0]->id,'BLOCKED');
				$this->session->sess_destroy();
				header('Location: /mgmt/login/banned');
			} else {
				$this->session->set_userdata('mid', $user[0]->id);
				$this->session->set_userdata('mname', $user[0]->name);
				$this->session->set_userdata('mposition', $user[0]->position);
				header('Location: /mgmt/');
			}
		} else {
			header('Location: /mgmt/login/error');
		}
	}
	}

	public function logout() {
		if ($this->checkPermission()) {
		if ($this->muser->getLastEntered($this->session->userdata('mid'))!='BLOCKED')
			$this->muser->setLastEntered($this->session->userdata('mid'),time()-2400);
		$this->session->sess_destroy();
		header('Location: /mgmt/login');
	}
	}

	public function addPartnerPerform(){
		if ($this->checkPermission()) {
		$pass = md5($_POST['pass']);
		$this->email->from('no-reply@godeal.kz', 'GoDeal');
		$this->email->to($_POST['email']);

		$this->email->subject('Партнерство с GoDeal');
		$this->email->message(generateRegisteredPartnerMessage($_POST['email'], $_POST['pass']));	

		$this->email->send();

		$this->partner->addPartner($_POST['name'],$_POST['phone'], 
			$_POST['email']
			,$pass);
		header('Location: /mgmt/#allPartners/page/1');
	}
	}

	public function viewDocuments() {
		if ($this->checkPermission()) {
		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		$this->load->view('mgmt/res/allPartners.php', $data);	
	}
	}

	//---------------------Category----------------

	public function allCategories() {
		if ($this->checkPermission()) {
		$data["last_page"] = 10;
		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		$data["categories"] = $this->category->getPageCategories() ;
		$this->load->view('mgmt/res/allCategories.php', $data);	
	}
	}

	public function addCategory() {
		if ($this->checkPermission()) {
		$this->load->view('mgmt/res/addCategory.php');
	}
	}

	public function deleteCategory(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->category->deleteCategory($param);

		echo "<h2>Успешно Удалено!</h2>";
		echo "<a class='btn btn-success'href='#allCategories/'>Далее</a>";
	}
	}

	public function addCategoryPerform() {
		if ($this->checkPermission()) {
		$this->category->addCategory($_POST['name']);
		header('Location: /mgmt/#allADeals/page/1');
	}
	}

	public function editCategory() {
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->db->where('id',$param);
		$query = $this->db->get('categories');
		$data['cat'] = $query->result();
		
		$this->load->view('mgmt/res/editCategory.php', $data);	
	}
	}

	public function editCategoryPerform() {
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->category->editCategory($param, $_POST['name']);
		header('Location: /mgmt/#allCategories/');
	}
	}

	public function viewCategory(){
		if ($this->checkPermission()) {
		$param = func_get_arg(1);
		$this->db->where('category',$param);
		$query = $this->db->get('adeals');
		$data['adeals'] = $query->result();
		$this->load->view('mgmt/res/viewCategory.php', $data);
	}
	}

	//-------------------Adeal----------------------

	public function allADeals() {
		if ($this->checkPermission()) {
		$data["last_page"] = 10;
		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		$data["adeals"] = $this->adeal->getPageDeals($data["page"]);

		$this->load->view('mgmt/res/allADeals.php', $data);	
	}
	}	

	public function addADealPerform() {
		if ($this->checkPermission()) {
		$config['upload_path'] = './images/';
		$config['allowed_types'] = 'gif|jpg|png|jpeg';
		$this->load->library('upload', $config);
		if ( ! $this->upload->do_upload()) {
			echo $this->upload->display_errors();
		} else {
			$data = $this->upload->data();
			$this->deal->setStatus($_POST['deal_id'], 3);
			$param = func_get_arg(1);
			$img_url = "/images/".$data["file_name"];
			// $title, $i_cost, $sale, $s_cost, $sale_end, $img_url, $sold, $address,
   //                    $time, $video, $specs, $cond, $coord,  $views, $likes,
   //                    $city, $tel, $category, $deal_id
			$this->adeal->addADeal($_POST['title'], $_POST['i_cost'], $_POST['sale'], $_POST['s_cost'], $_POST['sale_end'], 
				$img_url, $_POST['sold'], $_POST['address'],
		     	$_POST['time'], $_POST['video'], $_POST['specs'], $_POST['cond'], $_POST['coord'], $_POST['views'], $_POST['likes'],
		       	$_POST['city'], $_POST['phone'], $_POST['category'], $_POST['deal_id']);

			header('Location: /mgmt/#allADeals/page/1');
		}
	}
	}

	public function addListADeal() {
		if ($this->checkPermission()) {

		$data["last_page"] = 1;
		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		$this->db->where('status','2');
		$data["deals"] = $this->deal->getPageDeals($data["page"]);
		$this->load->view('mgmt/res/addListADeal.php', $data);	
	}
	}

	public function addADeal() {
		if ($this->checkPermission()) {

		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		$this->db->where('id',$data['id']);
		$res = $this->db->get('deals');
		$data['deals'] = $res->result();
		$data['categories'] = $this->category->getPageCategories();
		$this->load->view('mgmt/res/addADeal.php', $data);
	}
	}

	public function deleteAdeal(){
		if ($this->checkPermission()) {

		$param = func_get_arg(1);
		$this->db->delete('adeals', array('id' => $param));
		echo "<h2>Акция удалена с сайта!</h2>";
		echo "<a class='btn btn-success'href='#allADeals/page/1'>Далее</a>";
	}
	}

	public function editAdeal(){
		if ($this->checkPermission()) {

		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		$this->db->where('id',$data['id']);
		$res = $this->db->get('adeals');
		$data['adeals'] = $res->result();
		$data['deal_id'] = $data['did'];
		$data['categories'] = $this->category->getPageCategories();
		$this->load->view('mgmt/res/editAdeal.php', $data);
	}
	}

	public function viewAdeal(){
		if ($this->checkPermission()) {

		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		$this->db->where('id',$data['id']);
		$res = $this->db->get('adeals');
		$data['adeals'] = $res->result();
		$data['category'] = $this->category->getCategoryById($data['adeals'][0]->category);

		$this->load->view('mgmt/res/viewAdeal.php', $data);
	}
	}

	public function editAdealPerform(){
		if ($this->checkPermission()) {

		// $id, $title, $i_cost, $sale, $s_cost, $sale_end, $sold, $address,
  //                     $time, $video, $specs, $cond, $coord, $views, $likes,
  //                     $city, $tel, $category

		$param = func_get_arg(1);
		$config['upload_path'] = './images/';
		$config['allowed_types'] = 'gif|jpg|png|jpeg';
		$this->load->library('upload', $config);
		if ( ! $this->upload->do_upload()) {
		} else {
			$data = $this->upload->data();	
			$img_url = "/images/".$data["file_name"];
			$this->adeal->editColumn($_POST['id'], 'img_url', $img_url);
		}
			$this->adeal->editADealNoImage($_POST['id'], $_POST['title'], $_POST['i_cost'], $_POST['sale'], 
				$_POST['s_cost'], $_POST['sale_end'], $_POST['sold'], $_POST['address'],
		   	$_POST['time'], $_POST['video'], $_POST['specs'], $_POST['cond'], $_POST['coord'], $_POST['views'], $_POST['likes'],
		   	$_POST['city'], $_POST['phone'], $_POST['category']);

			header('Location: /mgmt/#allADeals/page/1');
		}
	}

	public function imageAdeal(){
		if ($this->checkPermission()) {

		$param = func_get_arg(1);
		$this->db->where('adeal_id', $param);
		$res = $this->db->get('adealimages');
		$data['images'] = $res->result();
		$data['did'] = func_get_arg(1);
		$this->load->view('mgmt/res/imageAdeal.php', $data);
	}
	}

	public function addAdealImage(){
		if ($this->checkPermission()) {

			$config['upload_path'] = './images/';
			$config['allowed_types'] = 'gif|jpg|png';
			$this->load->library('upload', $config);
			if ( ! $this->upload->do_upload()) {
				$error = array('error' => $this->upload->display_errors());
				$this->load->view('upload_error', $error);
			} else {
				$data = $this->upload->data();
				$img_url = "/images/".$data["file_name"];
				$data = array(
	    			'adeal_id' => func_get_arg(1),
	    		 'img_url' => $img_url,
	    		 );
	    		$this->db->insert('adealimages', $data);
			}
		}
		header("Location: /mgmt/#allADeals/page/1");
	}

	public function deleteADealImage(){
    	$this->db->where('img_id', $_GET['img']);
    	$this->db->delete('adealimages'); 
    	echo "<h1>Удалено</h1>	<a href='#alladeals/page/1'>назад</a>";
	}

	//----------------Comment------------

	public function allComments() {
		if ($this->checkPermission()) {

		$data["last_page"] = 10;
		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		$data["comments"] = $this->comment->getAllComments() ;
		$this->load->view('mgmt/res/allComments.php', $data);	
	}
	}	

	public function answerComment() {
		if ($this->checkPermission()) {

		$data["last_page"] = 10;
		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		$data["comments"] = $this->comment->getCommentById($data["id"]) ;
		$this->load->view('mgmt/res/answerComment.php', $data);	
	}
	}

	public function saveCommentAnswer() {
		if ($this->checkPermission()) {

		$param = func_get_arg(0);
		$this->comment->answerComment($param, $_POST["answer"]);
		echo func_get_arg(0).$_POST["answer"];
		//header("Location: /mgmt/#allComments/page/1");
	}
	}

	public function home() {
		if ($this->checkPermission()) {
			$this->load->view('mgmt/res/home.php');
		}
	}

	// ---------------FinanceReport--------------

	public function financeReport(){
		
		if($this->session->userdata('mposition') != 3) {
			
				if($this->input->post('rad') == 'manager'){
					$data['managerselected'] = $this->input->post('manager-select');
				}else if($this->input->post('rad') == 'partner'){
					$data['partnerselected'] = $this->input->post('partner-select');
				}
				$data['datefrom'] = $this->input->post('datefrom');
				$data['dateto'] = $this->input->post('dateto');
			
			$query = $this->db->get('deals');					
			$data['deals'] = $query->result();

			foreach ($data['deals'] as $deal) {
				
				if($this->session->userdata('mposition') == 2 || $this->session->userdata('mposition') == 1){
					if($deal->manager =! $this->session->userdata('mname')){
						continue;
					}
				}
				$data['coupon_bought'][$deal->id] = $this->coupon->getMoneyByDealId($deal->id);
				$data['coupon_active'][$deal->id] = $this->coupon->getActiveMoneyByDealId($deal->id);
				$data['count_bought'][$deal->id] = $this->coupon->getCountByDealId($deal->id);
				$data['count_active'][$deal->id] = $this->coupon->getActiveCountByDealId($deal->id);
				
			}

			$this->load->view('mgmt/res/financeReport.php', $data);

		} else echo "<h1>Нет прав</h1>";
	}


// Banners

	public function addBanner() {
		if ($this->checkPermission()) {
			$this->load->view('mgmt/res/addBanner.php');
		}
	}

	public function allBanners() {
		if ($this->checkPermission()) {
			$data['banners'] = $this->banner->getBanners();
			$this->load->view('mgmt/res/allBanners.php', $data);
		}
	}

	public function addBannerPerform() {
		if ($this->checkPermission()) {
			$config['upload_path'] = './images/banners/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg';
			$this->load->library('upload', $config);
			if ( ! $this->upload->do_upload()) {
				echo $this->upload->display_errors();
			} else {
				$data = $this->upload->data();
				$img_url = "/images/banners/".$data["file_name"];
				$this->banner->addBanner($img_url, '');

				header('Location: /mgmt/#allBanners');
			}
		}
	}

	public function addRightBannerPerform() {
		if ($this->checkPermission()) {
			$config['upload_path'] = './images/banners/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg';
			$this->load->library('upload', $config);
			if ( ! $this->upload->do_upload()) {
				$this->db->where('id', 1);
				$this->db->set('url', $_POST['url']);
				$this->db->update('right_banner');
			} else {
				$data = $this->upload->data();
				$img_url = "/images/banners/".$data["file_name"];

				$this->db->where('id', 1);
				$this->db->set('img_url', $img_url);
				$this->db->set('url', $_POST['url']);
				$this->db->update('right_banner');
			}
			header('Location: /mgmt/#rightBanner');
		}
	}

	public function deleteBanner() {
		if ($this->checkPermission()) {
			for ($i = 0; $i < func_num_args(); $i+=2) {
				$data[func_get_arg($i)] = func_get_arg($i + 1);
			}

			$this->banner->deleteBanner($data["id"]);

			echo "Удалено <a href='#allBanners' class='btn btn-success'>Все баннеры</a>";
		}
	}

	public function map() {
		$this->load->view('mgmt/map');
	}

	public function rightBanner() {
		$this->load->view('mgmt/res/rightBanner.php');
	}
}